﻿#region License
/* ---------------------------------------------------------------- *
 *
 * This file is part of the Xcoordination Application Space
 * ("XcoAppSpace") http://www.xcoordination.com
 *
 * Copyright (C) 2009 Xcoordination http://www.xcoordination.com
 *
 * XcoAppSpace is free software; you can redistribute it and/or
 * modify it under the terms of version 2 of the GNU General
 * Public License as published by the Free Software Foundation.
 *
 * XcoAppSpace is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/
 * or write to the Free Software Foundation, Inc., 51 Franklin
 * Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * ---------------------------------------------------------------- */
#endregion

using System;
using XcoAppSpaces.Contracts.Transport;
using System.IO;
using System.Transactions;
using System.Messaging;

namespace XcoAppSpaces.Transport.MSMQ
{
	internal class MSMQSend : IDisposable
	{
        private readonly MessageQueue msgQueue; //MessageQueue send to 
		private DateTime lastSendTime = DateTime.Now;
	    private TransferHelper transferHelper;

		public MSMQSend(string msgQueueName)
		{
            msgQueue = new MessageQueue(@"FormatName:Direct=OS:" + msgQueueName);
		    transferHelper = new TransferHelper();
		}

		public DateTime LastSendTime
		{
			get { return lastSendTime; }
		}

		public void Send(XcoMessage msg, string destAddress, string localAddress)
		{
            byte[] bytes = transferHelper.Convert(msg, localAddress);
            Message qMessage = new Message {BodyStream = new MemoryStream(bytes)};

		    //Create a transaction scope.
            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
            {
                msgQueue.Send(qMessage,MessageQueueTransactionType.Automatic);
                // Complete the transaction.
                scope.Complete();
            }
			lastSendTime = DateTime.Now;
		}

		public void Close()
		{
            if (msgQueue != null)
			{
                msgQueue.Close();
			}
		}

		public void Dispose()
		{
			Close();
		}
	}
}
